package net.sudot.chess.business.wechat.config;

import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import net.sudot.chess.business.wechat.api.WechatApiService;
import net.sudot.chess.business.wechat.handler.CustomerServiceHandler;
import net.sudot.chess.business.wechat.handler.KfSessionHandler;
import net.sudot.chess.business.wechat.handler.LogHandler;
import net.sudot.chess.business.wechat.handler.MsgHandler;
import net.sudot.chess.business.wechat.handler.NullHandler;
import net.sudot.chess.business.wechat.handler.SubscribeHandler;
import net.sudot.chess.business.wechat.handler.TemplateMsgHandler;
import net.sudot.chess.business.wechat.handler.UnsubscribeHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.concurrent.ExecutorService;

/**
 * 微信配置
 *
 * @author tangjialin on 2018-03-30.
 */
@Configuration
@EnableConfigurationProperties(WechatProperties.class)
public class WechatConfiguration {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    protected LogHandler logHandler;
    @Resource
    protected NullHandler nullHandler;
    @Resource
    protected KfSessionHandler kfSessionHandler;
    @Resource
    protected CustomerServiceHandler customerServiceHandler;
    @Resource
    protected MsgHandler msgHandler;
    @Resource
    protected UnsubscribeHandler unsubscribeHandler;
    @Resource
    protected SubscribeHandler subscribeHandler;
    @Resource
    protected TemplateMsgHandler templateMsgHandler;
    private WxMpMessageRouter router;
    @Resource
    private WechatProperties wechatProperties;

    @PreDestroy
    public void destroy() {
        try {
            if (logger.isInfoEnabled()) {
                logger.info("销毁微信工具线程池:me.chanjar.weixin.mp.api.WxMpMessageRouter.executorService");
            }
            Field field = router.getClass().getDeclaredField("executorService");
            field.setAccessible(true);
            ExecutorService executorService = (ExecutorService) field.get(router);
            executorService.shutdown();
        } catch (NoSuchFieldException e) {
            logger.warn("无法找到属性[me.chanjar.weixin.mp.api.WxMpMessageRouter.executorService] 错误信息:{}", e.getMessage());
        } catch (IllegalAccessException e) {
            logger.warn("属性[me.chanjar.weixin.mp.api.WxMpMessageRouter.executorService]执行错误 错误信息:{}", e.getMessage());
        }
    }

    @Bean
    public WechatInRedisConfigStorage configStorage() {
        WechatInRedisConfigStorage configStorage = new WechatInRedisConfigStorage();
        configStorage.setAppId(wechatProperties.getAppId());
        configStorage.setSecret(wechatProperties.getSecret());
        configStorage.setToken(wechatProperties.getToken());
        configStorage.setAesKey(wechatProperties.getAesKey());
        return configStorage;
    }

    @Bean
    public WechatApiService wechatApiService() {
//        WxMpService wxMpService = new me.chanjar.weixin.mp.api.impl.okhttp.WxMpServiceImpl();
//        WxMpService wxMpService = new me.chanjar.weixin.mp.api.impl.jodd.WxMpServiceImpl();
//        WxMpService wxMpService = new me.chanjar.weixin.mp.api.impl.apache.WxMpServiceImpl();
        WechatApiService wechatApiService = new WechatApiService();
        wechatApiService.setWxMpConfigStorage(configStorage());
        return wechatApiService;
    }

    @Bean
    public WxMpMessageRouter router(WechatApiService wechatApiService) {
        WxMpMessageRouter newRouter = new WxMpMessageRouter(wechatApiService);

        // 记录所有事件的日志
        newRouter.rule().handler(this.logHandler).next();

        // 接收客服会话管理事件
        newRouter.rule().async(false).msgType(WechatConsts.XmlMsgType.EVENT).event(WechatConsts.EVT_KF_CREATE_SESSION)
                .handler(this.kfSessionHandler).end();
        newRouter.rule().async(false).msgType(WechatConsts.XmlMsgType.EVENT).event(WechatConsts.EVT_KF_CLOSE_SESSION)
                .handler(this.kfSessionHandler).end();
        newRouter.rule().async(false).msgType(WechatConsts.XmlMsgType.EVENT).event(WechatConsts.EVT_KF_SWITCH_SESSION)
                .handler(this.kfSessionHandler).end();

        // 自定义菜单事件(转接客服,接入客服会话)
        newRouter.rule().async(false).msgType(WechatConsts.XmlMsgType.EVENT)
                .event(WechatConsts.MenuButtonType.CLICK).eventKey(WechatConsts.KefuMsgType.TRANSFER_CUSTOMER_SERVICE).handler(customerServiceHandler).end();

        // 点击菜单连接事件
        newRouter.rule().async(false).msgType(WechatConsts.XmlMsgType.EVENT)
                .event(WechatConsts.EventType.VIEW).handler(nullHandler).end();

        // 关注公众号事件
        newRouter.rule().async(false).msgType(WechatConsts.XmlMsgType.EVENT)
                .event(WechatConsts.EventType.SUBSCRIBE).handler(subscribeHandler).end();
        // 取消关注公众号事件
        newRouter.rule().async(false).msgType(WechatConsts.XmlMsgType.EVENT)
                .event(WechatConsts.EventType.UNSUBSCRIBE).handler(unsubscribeHandler).end();

        // 扫码事件
        newRouter.rule().async(false).msgType(WechatConsts.XmlMsgType.EVENT)
                .event(WechatConsts.EventType.SCAN).handler(subscribeHandler).end();

        // 模板消息发送结果事件
        newRouter.rule().async(false).msgType(WechatConsts.XmlMsgType.EVENT)
                .event(WechatConsts.EventType.TEMPLATE_SEND_JOB_FINISH).handler(templateMsgHandler).end();

        // 默认
        newRouter.rule().async(false).handler(msgHandler).end();
        router = newRouter;
        return newRouter;
    }

}
